package com.migrate.module.sharding.algorithm;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingValue;

import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * C端维度分表路由算法类
 *
 * @author zhonghuashishan
 */
public class OrderTableShardingByUserAlgorithm implements ComplexKeysShardingAlgorithm<Comparable<?>> {

    @Override
    public Collection<String> doSharding(Collection<String> tables, ComplexKeysShardingValue<Comparable<?>> shardingValue) {

        Map<String, Collection<Comparable<?>>> columnNameAndShardingValuesMap = shardingValue.getColumnNameAndShardingValuesMap();

        for (String key:columnNameAndShardingValuesMap.keySet()){
            Collection<Comparable<?>> comparables = columnNameAndShardingValuesMap.get(key);
            if (CollectionUtils.isNotEmpty(comparables)){
                // 获取配置的路由策略
                return comparables.stream()
                        .map(comparable -> getActualTableName(String.valueOf(comparable), tables))
                        .collect(Collectors.toSet());
            }
        }
        return null;
    }

        public String getActualTableName(String shardingValue, Collection<String> tables) {
            //获取userId后三位
            String userIdSuffix = StringUtils.substring(shardingValue, shardingValue.length() - 3);
            //使用userId后三位进行路由
            int tableSuffix = userIdSuffix.hashCode() / tables.size() % tables.size();
            for(String table : tables) {
                if(table.endsWith(String.valueOf(tableSuffix))) {
                    return table;
                }
            }
            return null;
    }

}